package br.com.sigad.servlets.documento;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet("/fileupload")
public class FileUpload extends HttpServlet {
	private static final String ARQUIVOS = "/arquivos";
	private static final long serialVersionUID = 1L;
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		System.out.println("CHEGOU NO SERVLET");
		// Create a factory for disk-based file items
		FileItemFactory factory = new DiskFileItemFactory();

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		if (ServletFileUpload.isMultipartContent(request)) { 
			try {
				List<FileItem> parseRequest = upload.parseRequest(request);
				criarDiretorioDeArmazenamento();
				for (FileItem item : parseRequest) {
					copiarArquivo((DiskFileItem) item);
				}
				response.getOutputStream().write("SUCESSO".getBytes());
				response.flushBuffer();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}

	}

	private void criarDiretorioDeArmazenamento() {
		File dir = new File( getServletContext().getRealPath("/")+ARQUIVOS);
		if (!dir.exists()) {
			dir.mkdir();
		}
	}

	private void copiarArquivo(DiskFileItem fileUploaded) throws IOException {
		FileOutputStream fos = null;
		try {
			File newFile = new File( getServletContext().getRealPath("/")+ARQUIVOS + File.separator
					+ fileUploaded.getName());

			fos = new FileOutputStream(newFile);
			fos.write(fileUploaded.get());
			fos.flush();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (fos != null) {
				fos.close();
			}
		}
	}
}
